﻿using Antares.Common;
using Antares.VIEWs;
using AntaresShell.Common;
using AntaresShell.NavigatorProvider;
using Repository.LiveConnection;
using Repository.Repositories;
using Repository.Sync;
using System;
using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace Antares
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    partial class ExtendedSplash
    {
        internal Rect SplashImageRect; // Rect to store splash screen image coordinates.
        internal bool Dismissed = false; // Variable to track splash screen dismissal status.
        internal ProgressRing Pr;
        private readonly SplashScreen _splash; // Variable to hold the splash screen object.


        public ExtendedSplash(SplashScreen splashscreen, bool loadState)
        {
            InitializeComponent();

            Window.Current.SizeChanged += ExtendedSplash_OnResize;

            _splash = splashscreen;

            if (_splash != null)
            {
                // Register an event handler to be executed when the splash screen has been dismissed.
                _splash.Dismissed += DismissedEventHandler;

                // Retrieve the window coordinates of the splash screen image.
                SplashImageRect = _splash.ImageLocation;
                PositionImage();
            }

            // Restore the saved session state if necessary
            RestoreStateAsync(loadState);
            //pr = new ProgressRing() { IsEnabled = true, IsActive = true };
            //ScaleTransform st = new ScaleTransform() { ScaleX = 2, ScaleY = 2 };
            //pr.RenderTransform = st;
            //RootGrid.Children.Add(pr);


            // Position the extended splash screen's progress ring.

            if (_splash == null) throw new ArgumentException("_splash = null");
            ProgressRing.SetValue(Canvas.TopProperty, _splash.ImageLocation.Y + _splash.ImageLocation.Height + 32);

            ProgressRing.SetValue(Canvas.LeftProperty,

                                  _splash.ImageLocation.X + (_splash.ImageLocation.Width / 2) - 15);
        }


        async void RestoreStateAsync(bool loadState)
        {
            if (loadState)
                await SuspensionManager.RestoreAsync();

            // Normally you should start the time consuming task asynchronously here and 
            // dismiss the extended splash screen in the completed handler of that task
            // This sample dismisses extended splash screen  in the handler for "Learn More" button for demonstration
        }

        // Position the extended splash screen image in the same location as the system splash screen image.
        void PositionImage()
        {
            extendedSplashImage.SetValue(Canvas.LeftProperty, SplashImageRect.X);
            extendedSplashImage.SetValue(Canvas.TopProperty, SplashImageRect.Y);
            extendedSplashImage.Height = SplashImageRect.Height;
            extendedSplashImage.Width = SplashImageRect.Width;

            onAppear.Begin();

            //var anime = new DoubleAnimation { To = Window.Current.Bounds.X, Duration = new Duration(new TimeSpan(0, 0, 0, 1)), EnableDependentAnimation = true };
            //var storyboard = new Storyboard();
            //Storyboard.SetTargetProperty(anime, "Height");
            //Storyboard.SetTarget(anime, extendedSplashImage);

            //storyboard.Children.Add(anime);
            //storyboard.Begin();
        }

        void ExtendedSplash_OnResize(Object sender, WindowSizeChangedEventArgs e)
        {
            // Safely update the extended splash screen image coordinates. This function will be fired in response to snapping, unsnapping, rotation, etc...
            if (_splash != null)
            {
                // Update the coordinates of the splash screen image.
                SplashImageRect = _splash.ImageLocation;
                PositionImage();
            }
        }

        // Include code to be executed when the system has transitioned from the splash screen to the extended splash screen (application's first view).
        async void DismissedEventHandler(SplashScreen sender, object e)
        {
            Dismissed = true;


            await Dispatcher.RunAsync(CoreDispatcherPriority.High, async () =>
            {
                await Signin();
                await WeatherRepository.Instance.GetWeatherInfoAsync();
                await LoadBuffer();

                
                blurring.Begin();
                

            });
        }
        

        private async Task Signin()
        {
            if (await LiveConnection.Instance.Signin())
            {
                await LoadBuffer();
            }
        }

        private async Task LoadBuffer()
        {
            await CategoryRepository.Instance.GetAllCategories();
            await PriorityRepository.Instance.GetAllPriorities();
            await RepeatTypeRepository.Instance.GetAllRepeatTypes();

            await ProjectMemberRepository.Instance.GetAllProjects(GlobalData.MyUserID);
            await TaskRepository.Instance.GetAllTasksForUser(GlobalData.MyUserID);
            await ProjectRepository.Instance.GetAllProjects();
        }

        private void blurring_Completed(object sender, object e)
        {
            var mainPage = new MainPage();
            Window.Current.Content = mainPage;
            Window.Current.Activate();
            //Associate the frame with a SuspensionManager key                                
            SuspensionManager.RegisterFrame(mainPage.RootFrame, "AppFrame");
            Navigator.Instance.SetRootFrame(mainPage.RootFrame);

            Navigator.Instance.NavigateTo(typeof(TimelineWeekPage));
        }
    }
}
